﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using WebApiClientCore;
using WebApiClientCore.Attributes;
using XUCore.Extensions;
using XUCore.NetCore;

namespace XUCore.WeChat.Apis
{
    public class AccessTokenApiFilter : ApiFilterAttribute
    {
        public override async Task OnRequestAsync(ApiRequestContext context)
        {
            var app = Web.Request.Query.ContainsKey("app") ? Web.Request.Query["app"].SafeString() : "";

            IWeChatTokenManager tokenManager = context.HttpContext.ServiceProvider.GetRequiredService<IWeChatTokenManager>();
            string accessToken = await tokenManager.GetAccessTokenAsync(app);
            context.HttpContext.RequestMessage.AddUrlQuery("access_token", accessToken);

            if (context.HttpContext.RequestMessage.Content != null)
            {
                var data = await context.HttpContext.RequestMessage.Content.ReadAsStringAsync();
                if (!string.IsNullOrEmpty(data))
                {
                    var logger = context.HttpContext.ServiceProvider.GetRequiredService<ILogger<AccessTokenApiFilter>>();
                    logger.LogInformation(data);
                }
            }

        }

        public override async Task OnResponseAsync(ApiResponseContext context)
        {
            if (context.HttpContext.ResponseMessage.Content != null && context.HttpContext.ResponseMessage.IsSuccessStatusCode)
            {
                var data = await context.HttpContext.ResponseMessage.Content.ReadAsStringAsync();
                if (!string.IsNullOrEmpty(data))
                {
                    var logger = context.HttpContext.ServiceProvider.GetRequiredService<ILogger<AccessTokenApiFilter>>();
                    logger.LogInformation(data);
                }
            }
        }
    }
}
